import axios from 'axios';
const baseUrl = process.env.VUE_APP_API_URL;

const instance = axios.create({
    baseURL: baseUrl
});

/**
 * 调用 API 的方法
 * @param {string} selectValue - 选择的值
 * @param {Object} dynamicParams - 动态参数
 * @param {Object} dynamicHeaders - 动态请求头
 * @param {Object} dynamicBody - 动态请求体
 * @param {number} timeout - 请求超时时间（毫秒）
 * @returns {Promise<Object>} - 返回一个 Promise，解析为 API 的响应数据
 */
export const callApi = async (selectValue, dynamicParams = {}, dynamicHeaders = {}, dynamicBody = {}) => {
    const params = {};

    // 对每个参数进行 URI 编码
    if (dynamicParams && Object.keys(dynamicParams).length > 0) {
        params.dynamicParams = encodeURIComponent(JSON.stringify(dynamicParams));
    }
    if (dynamicHeaders && Object.keys(dynamicHeaders).length > 0) {
        params.dynamicHeaders = encodeURIComponent(JSON.stringify(dynamicHeaders));
    }
    if (dynamicBody && Object.keys(dynamicBody).length > 0) {
        params.dynamicBody = encodeURIComponent(JSON.stringify(dynamicBody));
    }

    try {
        const response = await instance.get(`${baseUrl}/common/callApi/${selectValue}`, { params });
        return response.data;
    } catch (error) { /* 错误处理 */ }
}




/**
 * 执行sql查询 的方法
 * @param {string} selectValue - 选择的值
 * @param {number} timeout - 请求超时时间（毫秒）
 * @returns {Promise<Object>} - 返回一个 Promise，解析为 API 的响应数据
 */
export const executeQuery = async (selectValue, timeout = 5000) => {
    try {
        const response = await instance.get(`${baseUrl}/common/executeDbQuery/${selectValue}`, {
            timeout
        });
        return response.data;
    } catch (error) {
        if (axios.isAxiosError(error)) {
            if (error.code === 'ECONNABORTED') {
                throw new Error('请求超时，请重试');
            }
            throw new Error(`请求失败: ${error.message}`);
        }
        throw new Error('发生未知错误');
    }
}

// 获取 API 配置列表
export const getApiConfigs = async (pageNo, pageSize) => {
    return await instance.get(`${baseUrl}/v1/module/apiConfig/page?pageNo=${pageNo}&pageSize=${pageSize}`);
};

// 获取API 列表
export const getAllApiList = async (enabled) => {
    return await instance.get(`${baseUrl}/v1/module/apiConfig/list?enabled=${enabled}`);
};
//获取sql 列表
export const getAllSqlList = async () => {
    return await instance.get(`${baseUrl}/v1/module/dbQueryConfig/list`);
};

// 删除 API 配置
export const deleteApiConfig = async (id) => {
    return await instance.delete(`${baseUrl}/v1/module/apiConfig/${id}`);
};

// 保存或更新 API 配置
export const saveApiConfig = async (apiConfig) => {
    if (apiConfig.id) {
        return await instance.put(`${baseUrl}/v1/module/apiConfig/${apiConfig.id}`, apiConfig);
    } else {
        return await instance.post(`${baseUrl}/v1/module/apiConfig`, apiConfig);
    }
};

// 获取数据库连接配置列表
export const getDbConnectionConfigs = async (req) => {
    return await instance.get(`${baseUrl}/v1/module/dbConnectionConfig/list`, { params: req });
};
export const getDbConnectionConfigsPage = async (params) => {
    return instance.get(`${baseUrl}/v1/module/dbConnectionConfig/page`, { params });
};

export const addDbConnectionConfig = async (data) => {
    return instance.post(`${baseUrl}/v1/module/dbConnectionConfig`, data);
};

export const updateDbConnectionConfig = async (id, data) => {
    return instance.put(`${baseUrl}/v1/module/dbConnectionConfig/${id}`, data);
};

export const deleteDbConnectionConfigs = async (ids) => {
    return instance.delete(`${baseUrl}/v1/module/dbConnectionConfig/${ids}`, { data: { ids } });
};


export const getAuthConfigs = async (req) => {
    return await instance.get(`${baseUrl}/v1/module/authConfig/list`, { params: req });
};
export const fetchAuthConfigs = async (currentPage, pageSize) => {
    try {
        const response = await instance.get(`${baseUrl}/v1/module/authConfig/page?pageNo=${currentPage}&pageSize=${pageSize}`);
        return response;
    } catch (error) {
        console.error('获取 AUTH 配置列表失败:', error);
        throw error;
    }
};

// 删除认证配置
export const deleteAuthConfig = async (id) => {
    try {
        const response = await instance.delete(`${baseUrl}/v1/module/authConfig/${id}`);
        return response;
    } catch (error) {
        console.error('删除 AUTH 配置失败:', error);
        throw error;
    }
};

// 保存或更新认证配置
export const saveAuthConfig = async (authConfig) => {
    try {
        let response;
        if (authConfig.id) {
            response = await instance.put(`${baseUrl}/v1/module/authConfig/${authConfig.id}`, authConfig);
        } else {
            response = await instance.post(`${baseUrl}/v1/module/authConfig`, authConfig);
        }
        return response;
    } catch (error) {
        console.error('保存 AUTH 配置失败:', error);
        throw error;
    }
};


export const fetchQueryConfigs = async (currentPage, pageSize) => {
    try {
        const response = await axios.get(`${baseUrl}/v1/module/dbQueryConfig/page?pageNo=${currentPage}&pageSize=${pageSize}`);
        return response;
    } catch (error) {
        console.error('获取 query 配置列表失败:', error);
        throw error;
    }
};

// 删除查询配置
export const deleteQueryConfig = async (id) => {
    try {
        const response = await axios.delete(`${baseUrl}/v1/module/dbQueryConfig/${id}`);
        return response;
    } catch (error) {
        console.error('删除 query 配置失败:', error);
        throw error;
    }
};

// 保存或更新配置
export const saveQueryConfig = async (queryConfig) => {
    try {
        let response;
        if (queryConfig.id) {
            response = await axios.put(`${baseUrl}/v1/module/dbQueryConfig/${queryConfig.id}`, queryConfig);
        } else {
            response = await axios.post(`${baseUrl}/v1/module/dbQueryConfig`, queryConfig);
        }
        return response;
    } catch (error) {
        console.error('保存 query 配置失败:', error);
        throw error;
    }
};